package me.zhengjie.modules.forecast.rest;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.heshuo.amm.model.METMessage;
import com.heshuo.amm.model.METMessageError;
import com.heshuo.amm.model.METStation;
import com.heshuo.amm.model.PageInfo;
import com.heshuo.amm.model.User;
import com.heshuo.amm.service.IMETAuthorityService;
import com.heshuo.amm.service.IMETMessageService;
import com.heshuo.amm.service.IReceiveMessageService;
import com.heshuo.amm.service.remind.SendMessageRemind;

import cn.ait.amfp.exception.METMessageParseException;
import cn.ait.amfp.model.METMessageType;
import me.zhengjie.modules.forecast.dto.MessageDTO;
import me.zhengjie.modules.forecast.satview.SatViewDataServiceImpl;
import me.zhengjie.modules.monitor.config.LoggerQueue;
import me.zhengjie.modules.monitor.domain.LogMessage;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.UserDTO;
import me.zhengjie.utils.SecurityUtils;

/**
 * @author maxd
 * @date 2019-10-29
 */
@RestController
@RequestMapping("api")
public class MessageController {
	Logger log = LoggerFactory.getLogger(MessageController.class);
	@Autowired
	IMETAuthorityService mETAuthorityService;
	@Autowired
	IMETMessageService iMETMessageService;
	@Autowired
	IReceiveMessageService iReceiveMessageService;
    @Autowired
    private UserService userService;

	@PostMapping(value = "/buildMessage")
	public ResponseEntity buildMessage(@RequestBody MessageDTO vmsg) {
		try {
			int validHour = 9;
			String c = vmsg.getCatgory();
			if ("FC".equals(c))
				validHour = 9;
			else if ("FT24".equals(c))
				validHour = 24;
			else if ("FT30".equals(c))
				validHour = 30;
			METStation metStation = mETAuthorityService.getMETStationBycode(vmsg.getAirport());
			SatViewDataServiceImpl svdsi = new SatViewDataServiceImpl();
			SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			log.info("getPointGrid params:" + ft.format(vmsg.getPublishTime()) + "," + metStation.getLongitude() + ","
					+ metStation.getLatitude() + ", " + "T2,WIND" + " ," + "WRF" + "," + validHour);
			Map<String, Integer> result = svdsi.getPointGrid(ft.format(vmsg.getPublishTime()), metStation.getLongitude(),
					metStation.getLatitude(), "T2,WIND", "WRF", validHour);
			log.info("getPointGrid result:" + result);
			log.info("getPointGrid validHour:" + validHour);

			return new ResponseEntity(result, HttpStatus.OK);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("",e);
		}catch(Throwable e){
			log.error("Web service not available.",e);
		}
		return new ResponseEntity(new HashMap(), HttpStatus.OK);
	}

	@GetMapping(value = "/getCurrentTime")
	public ResponseEntity getCurrentTime() {
		Date utc = getUTCDateTime();
		Date bj = getLocalDateTimeFromUTC(utc);
		Map<String,String> timeMap= new HashMap<String,String>();
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm") ;
		timeMap.put("utc", format.format(utc));
		timeMap.put("bj", format.format(bj));
		return new ResponseEntity(timeMap, HttpStatus.OK);
	}

	/**
     * 得到UTC时间，类型为字符串，格式为"yyyy-MM-dd HH:mm"<br />
     * 如果获取失败，返回null
     * @return
     */
    public  String getUTCTimeStr() {
    	DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm") ;
        StringBuffer UTCTimeBuffer = new StringBuffer();
        // 1、取得本地时间：
        Calendar cal = Calendar.getInstance() ;
        // 2、取得时间偏移量：
        int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET);
        // 3、取得夏令时差：
        int dstOffset = cal.get(java.util.Calendar.DST_OFFSET);
        // 4、从本地时间里扣除这些差量，即可以取得UTC时间：
        cal.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset));
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH)+1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE); 
        UTCTimeBuffer.append(year).append("-").append(month).append("-").append(day) ;
        UTCTimeBuffer.append(" ").append(hour).append(":").append(minute) ;
        try{
            format.parse(UTCTimeBuffer.toString()) ;
            return UTCTimeBuffer.toString() ;
        }catch(ParseException e)
        {
            e.printStackTrace() ;
        }
        return null ;
    }
    /**
     * 将UTC时间转换为东八区时间
     * @param UTCTime
     * @return
     */
    public static String getLocalTimeFromUTC(String UTCTime){
    	DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm") ;
        java.util.Date UTCDate = null ;
        String localTimeStr = null ;
        try {
            UTCDate = format.parse(UTCTime);
            format.setTimeZone(TimeZone.getTimeZone("GMT-8")) ;
            localTimeStr = format.format(UTCDate) ;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return localTimeStr ;
    }

    public Date getUTCDateTime(){
    	 // 1、取得本地时间：
        Calendar cal = Calendar.getInstance() ;
        // 2、取得时间偏移量：
        int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET);
        // 3、取得夏令时差：
        int dstOffset = cal.get(java.util.Calendar.DST_OFFSET);
        // 4、从本地时间里扣除这些差量，即可以取得UTC时间：
        cal.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset));
        return cal.getTime();
    }

    public Date getLocalDateTimeFromUTC(Date utcDate){
    	Calendar calendar = Calendar.getInstance();
        calendar.setTime(utcDate);
        calendar.add(Calendar.HOUR,  8);
        return  calendar.getTime();
    }
	@PostMapping(value = "/validate")
	public ResponseEntity validate(@RequestBody MessageDTO vmsg) {
		METMessage msg = com.heshuo.amm.model.METMessageFactory.createMetMessage(
				METMessageType.valueOf(vmsg.getCatgory().substring(0, 2)), vmsg.getAirport(), "39",
				vmsg.getPublishTime());
		msg.updateHeaderAndContent(vmsg.getAirport(), vmsg.getPublishTime());
		msg.updateHeaderAndContent(vmsg.getContent());
		try {
			boolean b = msg.validate();
		} catch (METMessageParseException e) {
			METMessageError mme = new METMessageError(msg);
			String errMsg = mme.getErrorMessage(e, true);
			List msgs = new ArrayList();
			msgs.addAll(java.util.Arrays.asList(errMsg.replace("<html><body>错误信息：<br>", "").replace("<br></body></html>", "").split("<br>")));
			return new ResponseEntity(msgs, HttpStatus.OK);
		}
		return new ResponseEntity(true, HttpStatus.OK);
	}

	@PostMapping(value = "/send")
	public ResponseEntity send(@RequestBody MessageDTO vmsg) {
		METMessage msg = com.heshuo.amm.model.METMessageFactory.createMetMessage(
				METMessageType.valueOf(vmsg.getCatgory().substring(0, 2)), vmsg.getAirport(), "39",
				vmsg.getPublishTime());
		msg.updateHeaderAndContent(vmsg.getAirport(), vmsg.getPublishTime());
		msg.updateHeaderAndContent(vmsg.getContent());
		try {
			boolean b = msg.validate();
			if (b) {
				msg.setUsername(vmsg.getAirport());
				msg.setPublishStatus(METMessage.STATUS_COMMIT);
				iMETMessageService.send(msg, 1, true);
			} else {
				return new ResponseEntity(false, HttpStatus.OK);
			}
		} catch (METMessageParseException e) {
			METMessageError mme = new METMessageError(msg);
			String errMsg = mme.getErrorMessage(e, true);
			List msgs = new ArrayList();
			msgs.addAll(java.util.Arrays.asList(errMsg.replace("<html><body>错误信息：<br>", "").replace("<br></body></html>", "").split("<br>")));
			return new ResponseEntity(msgs, HttpStatus.OK);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResponseEntity(false, HttpStatus.OK);
		}
		return new ResponseEntity(true, HttpStatus.OK);
	}

	@PostMapping(value = "/save")
	public ResponseEntity save(@RequestBody MessageDTO vmsg) {
		METMessage msg = com.heshuo.amm.model.METMessageFactory.createMetMessage(
				METMessageType.valueOf(vmsg.getCatgory().substring(0, 2)), vmsg.getAirport(), "39",
				vmsg.getPublishTime());
		msg.updateHeaderAndContent(vmsg.getAirport(), vmsg.getPublishTime());
		msg.updateHeaderAndContent(vmsg.getContent());
		
		try {
//			boolean b = msg.validate();保存报文时不校验
			boolean b = true;
			if (b) {
				msg.setUsername(vmsg.getAirport());
				msg.setPublishStatus(METMessage.STATUS_SUCCESS);
				iMETMessageService.saveMessage(msg);
				LogMessage logMsg = new LogMessage("您有新的待处理报文需要发布！",null,null,"newMessage"+msg.getObcc(),"OTHER");
				LoggerQueue.getInstance().push(logMsg);
			} else {
				return new ResponseEntity(false, HttpStatus.OK);
			}
		} catch (METMessageParseException e) {
			METMessageError mme = new METMessageError(msg);
			String errMsg = mme.getErrorMessage(e, true);
			List msgs = new ArrayList();
			msgs.addAll(java.util.Arrays.asList(errMsg.replace("<html><body>错误信息：<br>", "").replace("<br></body></html>", "").split("<br>")));
			return new ResponseEntity(msgs, HttpStatus.OK);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResponseEntity(false, HttpStatus.OK);
		}
		return new ResponseEntity(true, HttpStatus.OK);
	}


	@GetMapping(value="/message/queryReceiveMessage")
	public ResponseEntity queryReceiveMessage(@RequestParam(value = "start", required = false) Date start,
			@RequestParam(value = "end", required = false) Date end,
			@RequestParam(value = "address", required = false) String address,
			@RequestParam(value = "type", required = false) String type,
			@RequestParam(value = "cccc", required = false) String cccc,
			@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "limit", required = false, defaultValue = "10") int limit) {

		if(page<=0)page=1;
		PageInfo pi =  iReceiveMessageService.getMessages(start, end,
		 address, null, null, page, limit);
		Map res = new HashMap();
		res.put("totalElements", pi.getResults().size());
		res.put("content", pi.getResults());
		return new ResponseEntity(res, HttpStatus.OK);
	}
	@GetMapping(value="/message/querySendMessage")
	public ResponseEntity querySendMessage(@RequestParam(value = "start", required = false) Date start,
			@RequestParam(value = "end", required = false) Date end,
			@RequestParam(value = "types", required = false) String types,
			@RequestParam(value = "status", required = false) String status,
			@RequestParam(value = "users", required = false) String users,
			@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "limit", required = false, defaultValue = "10") int limit) {
		UserDTO userDto = userService.findById(SecurityUtils.getUserId());
		List<User> listUser = new ArrayList();
		if(null!=userDto.getDept().getAirportCode()){
			User u1 = new User();
			u1.setUsername(userDto.getDept().getAirportCode());
			listUser.add(u1);
		}
		
		if(page<=0)page=1;
		PageInfo pi =  iMETMessageService.getMessages(start, end,
		 null, null, listUser, page, limit);
		
		Map res = new HashMap();
		res.put("totalElements", pi.getResults().size());
		res.put("content", pi.getResults());
		return new ResponseEntity(res, HttpStatus.OK);
	}
	@GetMapping(value="/message/findLastMessage")
	public ResponseEntity findLastMessage(@RequestParam(value="msgType") String msgType,@RequestParam(value="aerodrome") String aerodrome){

		if(msgType.startsWith("FT"))msgType="FT";
		METMessage msg =  iMETMessageService.findLatestMETMessage(METMessageType.valueOf(msgType), aerodrome);
		return new ResponseEntity(msg,HttpStatus.OK);
	}
	

}
